<template>
  <div class="search-form">
    <el-form 
      ref="formRef" 
      :model="searchForm" 
      :inline="true" 
      label-width="auto"
      @submit.prevent="handleSearch"
    >
      <slot :form="searchForm"></slot>
      <el-form-item>
        <el-button type="primary" @click="handleSearch">
          <el-icon><Search /></el-icon>
          搜索
        </el-button>
        <el-button @click="handleReset">
          <el-icon><Refresh /></el-icon>
          重置
        </el-button>
        <el-button 
          v-if="showToggle && hasMoreFields" 
          type="text" 
          @click="toggleExpanded"
        >
          {{ expanded ? '收起' : '展开' }}
          <el-icon>
            <ArrowUp v-if="expanded" />
            <ArrowDown v-else />
          </el-icon>
        </el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { ref, reactive, watch } from 'vue'
import { Search, Refresh, ArrowUp, ArrowDown } from '@element-plus/icons-vue'

const props = defineProps({
  modelValue: {
    type: Object,
    default: () => ({})
  },
  showToggle: {
    type: Boolean,
    default: false
  },
  hasMoreFields: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['update:modelValue', 'search', 'reset'])

const formRef = ref()
const expanded = ref(false)
const searchForm = reactive({ ...props.modelValue })

// 监听表单数据变化
watch(searchForm, (newVal) => {
  emit('update:modelValue', newVal)
}, { deep: true })

// 监听外部数据变化
watch(() => props.modelValue, (newVal) => {
  Object.assign(searchForm, newVal)
}, { deep: true })

const handleSearch = () => {
  emit('search', searchForm)
}

const handleReset = () => {
  formRef.value?.resetFields()
  emit('reset')
}

const toggleExpanded = () => {
  expanded.value = !expanded.value
}

defineExpose({
  resetFields: () => formRef.value?.resetFields(),
  validate: () => formRef.value?.validate(),
  expanded
})
</script>

<style lang="scss" scoped>
.search-form {
  background: #fff;
  padding: 16px;
  margin-bottom: 16px;
  border-radius: 6px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);

  :deep(.el-form-item) {
    margin-bottom: 16px;
  }

  :deep(.el-form-item:last-child) {
    margin-bottom: 0;
  }
}
</style>